<?php
// 退货

!defined('IN_SYSTEM') && exit('Access denied');

class tuihuoControlPage extends commonControlPage 
{
	/*退货单列表*/
	public function listModule() 
	{
		$this->view->opt='view';
		$this->view->view_act=' class="active" '; 	
		$this->doTuiHuoList();
		$this->showMainPage('admincp/tuihuo/tuihuo_list');
	}


	/*退货单列表*/
	public function viewinfoModule() 
	{
		$tid = $_REQUEST['tid'];
		if(!$tid)
		{
			$this->showMessage('非法操作','back');
		}	
		$tuihuo = tuihuoEntity::GetRow($tid);
        if (!$tuihuo) $this->showMessage('退货单不存在','back');
		$this->view->tuikuan_product_list = tuihuoEntity::Gettuihuodetails($tid );  			
		$this->view->tuihuo = $tuihuo;   
		$this->view->tid= $tid;									 
		$this->view->opt='post';
		$this->view->post_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_list');	
	}

	


	/* 
	* 选择订单
	*/
	public function applicationModule()
	{
		$where = " audit_state='6' or audit_state ='5' and istuihuo='0' ";
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		$this->view->order_list = $this->PrePage('order','order_id',$where,$page,'order_id desc');
		$this->view->opt='view';
		$this->view->view_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_application');		
	}
	
	/* 
	* 填写退货信息
	*/
	public function applicinfoModule()
	{
		$oid = $_REQUEST['oid'];
		if(!$oid)
		{
			$this->showMessage('非法操作','back');
		}	
		$order = orderEntity::GetRow($oid);
        if (!$order) $this->showMessage('订单不存在','back');
				
		if (POST && AJAX) 
		{
			if(!class_permission::ValidateNodeByUser($_ENV['config']['tuihuo_post_audit_node'],$_POST['next_users']))
			{
				$this->outputJson(0,'退货审核被指派的用户没有权限');
			}
             
			$productcount = array_filter($_POST['productcount']);
			if(count($productcount)==0)
			{
				$this->outputJson(0,'请选择退货产品数量!');
			}
			// 获取该订单的所有商品列表
			$products = orderEntity::GetOrderDetail($oid);
			foreach((array)$products as $key=>$value)
			{
				if($productcount[$value['product_id']] && $value['product_num'] < intval($productcount[$value['product_id']]))
				{
					$this->outputJson(0,'商品['.$value['product_name'].']超过数量!');
				}
			}
			/*[开启事务]*/
			$_ENV['db']->beginTransaction();
			$sql = 'INSERT INTO `tuihuom` '.$this->buildSql(array(
                                'order_id' => $oid ,
                                'customer_id'   => $order['customer_id'],
                                'customer_name' => $order['customer_name'],
                                'bank_name' => $_POST['bank_name'],
                                'bank_no' => $_POST['bank_no'],
                                'audit_state' =>'待审核',
                                'created_time' => $_ENV['time'],
                                'audit1_uid' => $_POST['next_users'],
                                'co_member_id' => $this->user['uid'],
								'username'=>  $this->user['username'],
                            ));
			$_ENV['db']->runSql($sql);
            $tid = $_ENV['db']->insertId();
			if (!$tid) 
             {
                 /*[回滚事务]*/
	 			 $_ENV['db']->rollback();
                 $this->outputJson(0,'系统异常，退货单提交失败');
             }
		
			$totalprice = 0;
			foreach((array)$products as $key=>$value)
			{
				if($productcount[$value['product_id']])
				{
					$tempdata = array(
								'mid'=>$tid,
								'product_id'=>$value['product_id'],
								'product_name'=>$value['product_name'],
								'price'=>$value['product_pprice'],
								'product_num'=>$productcount[$value['product_id']],
								);
					$detailid = InsertTable('tuihuod', $tempdata); 
						if (!$detailid) 
						{
							 /*[回滚事务]*/
							 $_ENV['db']->rollback();
							 $this->outputJson(0,'系统异常，退货明细保存失败');
						}
					$totalprice+=$value['product_pprice']*$productcount[$value['product_id']];
				}
			}
			
			tuihuoEntity::UpdatePrice(array('pprice'=>$totalprice),$tid);
			
			/*[提交事务]*/
			$_ENV['db']->commit();
			$this->outputJson(0,'操作成功！');
		}
				
		$this->view->order_product_list = orderEntity::GetOrderDetails($oid);        //订单关联的商品列表
		$this->view->order = $order;      
		 			
		/*银行列表*/
		$this->view->banks = BindCombox("bank_name","bank_name",explode("\n",$_ENV['config']['bank_list']),'');	
		
		
		$users_html = '<select name="next_users" id="next_uid">';                         
		$users =  class_permission::GetUsersByNodes($_ENV['config']['tuihuo_post_audit_node']);			
        foreach ((array)$users as $user) 
		{
            $users_html .= '<option value="'.$user['uid'].'">'."{$user['username']}[{$user['nickname']}]".'</option>';
        }
        $users_html .= '</select>';
			
		$this->view->oid= $oid;
		$this->view->users_html = $users_html;											 
		$this->view->opt='post';
		$this->view->post_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_application');		
	}

	/* 
	* 审核退货信息
	*/
	public function auditinfoModule()
	{
		$tid = $_REQUEST['tid'];
		if(!$tid)
		{
			$this->showMessage('非法操作','back');
		}	
		$tuihuo = tuihuoEntity::GetRow($tid);
        if (!$tuihuo) $this->showMessage('退货单不存在','back');
			
		if (POST && AJAX) 
		{
			$param = array(
						'audit1_uid'=>$this->user['uid'],
						'audit1_username'=>$this->user['username'],
						'audit1_dateline'=>$_ENV['time'],
						'audit1_yijian'=>$_POST['audit1_yijian'],
						'audit_state'=>'已审核',
						);
			UpdateTable('tuihuom',$param,array('tid'=>$tid));
			$this->outputJson(0,'操作成功！');
		}
		$this->view->tuikuan_product_list = tuihuoEntity::Gettuihuodetails($tid );  			
		$this->view->tuihuo = $tuihuo;   
		$this->view->tid= $tid;									 
		$this->view->opt='post';
		$this->view->post_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_audit');	
	}
	
	/* 
	* 退货审核
	*/
	public function auditModule()
	{
		$where = " audit_state='待审核' ";
		
		if (!in_array($this->user['uid'],$_ENV['config']['superadmin'])) 
		{
                $where .= "  and audit1_uid='".$this->user['uid']."'  ";
        }
		
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		$this->view->tuihuo_list = $this->PrePage('tuihuom','tid',$where,$page,'tid desc');
		$this->view->opt='view';
		$this->view->view_act=' class="active" '; 	
		$this->showMainPage('admincp/tuihuo/tuihuo_audit');	
	}
	
	
	
	/* 
	* 退货入库
	*/
	public function instockModule()
	{
		$where = " audit_state='已审核' ";
		
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		$this->view->tuihuo_list = $this->PrePage('tuihuom','tid',$where,$page,'tid desc');
		$this->view->opt='view';
		$this->view->view_act=' class="active" '; 	
		$this->showMainPage('admincp/tuihuo/tuihuo_instock');	
	}
	
	
	/* 
	* 确认入库
	*/
	public function instockinfoModule()
	{
		$tid = $_REQUEST['tid'];
		if(!$tid)
		{
			$this->showMessage('非法操作','back');
		}	
		$tuihuo = tuihuoEntity::GetRow($tid);
        if (!$tuihuo) $this->showMessage('退货单不存在','back');
			
		if (POST && AJAX) 
		{
			$param = array(
						'audit_state'=>'已入库',
						);
			UpdateTable('tuihuom',$param,array('tid'=>$tid));
			$this->outputJson(0,'操作成功！');
		}
		$this->view->tuikuan_product_list = tuihuoEntity::Gettuihuodetails($tid );  			
		$this->view->tuihuo = $tuihuo;   
		$this->view->tid= $tid;									 
		$this->view->opt='post';
		$this->view->post_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_instock');		
	}
	
	/* 
	* 退货财务
	*/
	public function caiwuModule()
	{
		$where = " audit_state='已入库' ";
		
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		$this->view->tuihuo_list = $this->PrePage('tuihuom','tid',$where,$page,'tid desc');
		$this->view->opt='view';
		$this->view->view_act=' class="active" '; 	
		$this->showMainPage('admincp/tuihuo/tuihuo_caiwu');	
	}
	
	
	/* 
	* 确认财务
	*/
	public function caiwuinfoModule()
	{
		$tid = $_REQUEST['tid'];
		if(!$tid)
		{
			$this->showMessage('非法操作','back');
		}	
		$tuihuo = tuihuoEntity::GetRow($tid);
        if (!$tuihuo) $this->showMessage('退货单不存在','back');
			
		if (POST && AJAX) 
		{
			
			/*[开启事务]*/
			$_ENV['db']->beginTransaction();
			
			$param = array(
						'audit_state'=>'已完结',
						);
			UpdateTable('tuihuom',$param,array('tid'=>$tid));
			
			
			/*[库存修改]*/
			#获取订单商品ID和购买数量
            $opin = $_ENV['db']->fetchAll("SELECT product_num,product_id FROM tuihuod WHERE mid = {$tid} ");
            foreach ($opin as $p) 
			{
               	$run_row = $_ENV['db']->runSql("UPDATE `product` SET `num` = `num`+{$p['product_num']},`sold_num`=sold_num-{$p['product_num']} WHERE `product_id` = '{$p['product_id']}'");
                if (!$run_row) 
			    {
					/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->outputJson(0,'更改库存失败');
                 }
				 
				$run_row2 = $_ENV['db']->runSql("update order_detail set product_num=product_num-{$p['product_num']} WHERE `product_id` = '{$p['product_id']}'");
				 if (!$run_row2) 
			    {
					/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->outputJson(0,'更改库存失败');
                 }
				 
            }
			
			/*[提交事务]*/
			$_ENV['db']->commit();
			$this->outputJson(0,'操作成功！');
		}
		$this->view->tuikuan_product_list = tuihuoEntity::Gettuihuodetails($tid );  			
		$this->view->tuihuo = $tuihuo;   
		$this->view->tid= $tid;									 
		$this->view->opt='post';
		$this->view->post_act=' class="active" '; 
		$this->showMainPage('admincp/tuihuo/tuihuo_caiwu');		
	}
	
	/* 
	* 根据查询条件查询请假信息
	*/
	private function doTuiHuoList($audit_state='') 
	{	
		//日期选择控件JS
		$this->view->addScript('rili');
		$where = '1';
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		if($_GET['start_date'] && $_GET['end_date'])
		{
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		
		if ($audit_state) {
			$where .= ' and `audit_state` = '.$audit_state;
		}
        if ($this->user['uid'] && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) {
            $where .= ' and `co_member_id` = '.$this->user['uid'] ;
        }
		
		$this->view->tuihuo_list = $this->PrePage('tuihuom','tid',$where,$page,'tid desc');
	}
	
	
	
	//验证时间格式
	private function checkDateFormat() 
	{
        $start_date = $_GET['start_date'];
        $end_date = $_GET['end_date'];
		$this->view->start_date = $start_date;   //开始时间
		$this->view->end_date = $end_date;       //结束时间
        if (!ValidateDate($start_date) || !ValidateDate($end_date)) {
            $this->showMessage('日期格式错误','back');
        }
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date." 23:59:59");
        if ($start_date > $end_date) {
            $this->showMessage('结束时间必须小于开始时间','back');
        }
        if (($end_date-$start_date) > 31536000) {
            $this->showMessage('所选日期时间段超过了1年','back');
        }	
        return array('s'=>$start_date,'e'=>$end_date);
    }
	
	
}
?>